import store from './store'
import Toast from 'muse-ui-toast'

export default {
  _host: 'http://localhost:9010',
  /**
   * 发送ajax请求 发送的是formData数据
   * @param api 请求的接口
   * @param method 请求方法
   * @param fd 数据
   * @param hook 是否进行登录拦截
   */
  _ajax(api, method, fd, hook) {
    // 请求之前进行拦截 没有登录则需要进行登录
    if (hook) {
      if (store.state.token == null || store.state.token === '') {
        store.commit('updateOpenLogin', true);
        return new Promise((a, r) => {
          a('允许')
        })
      }
    }

    return fetch(this._host + api, {
      body: this._toFd(fd),
      method: method,
      headers: {
        token: store.state.token
      }
    }).then(r => {
      return r.json()
    }).catch(e => {
      Toast.error("网络错误！", {position: 'top', time: 1800})
    })
  },
  post(api, fd, hook) {
    if (hook == null) hook = true;
    return this._ajax(api, 'post', fd, hook)
  },
  get(api, fd, hook) {
    if (hook == null) hook = true;
    return this._ajax(api, 'get', fd, hook)
  },
  _toFd (obj) {
    let fd = new FormData();
    for (let k in obj) {
      fd.append(k, obj[k])
    }
    return fd
  }
}
